package com.jevons.muffin.vm;


import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;

import androidx.lifecycle.LifecycleOwner;

import com.jevons.muffin.activity.BaseView;
import com.jevons.muffin.net.exception.ResponseException;
import com.jevons.muffin.net.inter.BaseObserver;
import com.jevons.muffin.utilcode.StringUtils;
import com.jevons.muffin.widget.CustomToast;

/**
 * MVP模式-Presenter基类
 * @author linaisheng
 * Created at 2018/12/19.
 */

public class BasePresenter<V extends BaseView, MV extends BaseViewModel> implements BaseObserver {

    protected MV viewModel;

    private V mvpView;

    public BasePresenter() {
    }

    public BasePresenter(MV viewModel) {
        this.viewModel = viewModel;
    }

    /**
     * 绑定View
     * @param mvpView   需要绑定的View
     */
    public void attachView(V mvpView) {
        this.mvpView = mvpView;
    }

    /**
     * 解绑View
     */
    public void detachView() {
        this.mvpView = null;
    }

    /**
     * 判断View是否已绑定
     * @return
     */
    public boolean isViewAttached() {
        return mvpView != null;
    }

    /**
     * 获取已绑定的View
     * @return
     */
    public V getView() {
        return mvpView;
    }


    public void initViewed() {

    }


    /**
     * 获取已绑定View的上下文
     * @return
     */
    public Context getContext() {
        if (mvpView != null) {
            return mvpView.getContext();
        }
        return null;
    }

    protected LifecycleOwner getLifecycleOwner() {
        if (mvpView != null) {
            return mvpView.getLifecycleOwner();
        }
        return null;
    }

    protected void startActivity(Class clz) {
        if (getContext() != null) {
            getContext().startActivity(new Intent(getContext(), clz));
        }
    }


    @Override
    public void responseSuccess(String taskId, Object response) {
        if (isViewAttached()) {
            getView().hideLoading();
        }
    }


    @Override
    public void responseError(String taskId, ResponseException exception) {
        if (isViewAttached()) {
            getView().hideLoading();
        }
        if (!StringUtils.isEmpty(exception.getDescription())) {
            CustomToast.longShow(exception.getDescription());
        } else {
            CustomToast.longShow("请求失败请重试");
        }
    }

    protected View inflate(int resource) {
        return LayoutInflater.from(getContext()).inflate(resource, null);
    }

}
